import { defineStore } from "pinia";
import {
  type cacheType,
  store,
  debounce,
  ascending,
  getKeyList,
  filterTree,
  constantMenus,
  filterNoPermissionTree,
  formatFlatteningRoutes
} from "../utils";
import { useMultiTagsStoreHook } from "./multiTags";

export const usePermissionStore = defineStore({
  id: "pure-permission",
  state: () => ({
    // 静态路由生成的菜单
    constantMenus,
    // 整体路由生成的菜单（静态、动态）
    wholeMenus: [],
    // 整体路由（一维数组格式）
    flatteningRoutes: [],
    // 缓存页面keepAlive
    cachePageList: []
  }),
  actions: {
    /** 组装整体路由生成的菜单 */
    handleWholeMenus(routes : any[]) {
      console.log("===== handleWholeMenus被调用 =====");
      console.log("参数routes类型:", typeof routes);
      console.log("参数routes是否数组:", Array.isArray(routes));
      console.log("参数routes长度:", routes?.length);

      try {
        // 防止传入null或undefined
        if (!routes || !Array.isArray(routes)) {
          console.warn("handleWholeMenus接收到的参数不是数组，使用空数组代替");
          routes = [];
        }

        // 合并静态菜单和动态路由
        const mergedMenus = [...this.constantMenus];

        // 安全地添加动态路由，防止出现null或undefined项
        // if (routes.length > 0) {
        //   for (const route of routes) {
        //     if (route) {
        //       mergedMenus.push(route);
        //     }
        //   }
        // }
        console.log('mergedMenus-----', mergedMenus)

        console.log("合并后的菜单数量:", mergedMenus.length);

        // 按照rank排序
        const ascendingMenus = ascending(mergedMenus);

        // 只过滤showLink为false的菜单，不进行权限过滤
        this.wholeMenus = filterTree(ascendingMenus);
        console.log("生成的菜单数量:", this.wholeMenus.length);

        // 处理扁平化路由
        this.flatteningRoutes = formatFlatteningRoutes(mergedMenus);
        console.log("扁平化路由数量:", this.flatteningRoutes.length);
      } catch (error) {
        console.error("处理菜单时出错:", error);
        // 出错时使用默认值，确保应用不会崩溃
        this.wholeMenus = [];
        this.flatteningRoutes = [];
      }
    },
    cacheOperate({ mode, name } : cacheType) {
      const delIndex = this.cachePageList.findIndex(v => v === name);
      switch (mode) {
        case "refresh":
          this.cachePageList = this.cachePageList.filter(v => v !== name);
          break;
        case "add":
          this.cachePageList.push(name);
          break;
        case "delete":
          delIndex !== -1 && this.cachePageList.splice(delIndex, 1);
          break;
      }
      /** 监听缓存页面是否存在于标签页，不存在则删除 */
      debounce(() => {
        let cacheLength = this.cachePageList.length;
        const nameList = getKeyList(useMultiTagsStoreHook().multiTags, "name");
        while (cacheLength > 0) {
          nameList.findIndex(v => v === this.cachePageList[cacheLength - 1]) ===
            -1 &&
            this.cachePageList.splice(
              this.cachePageList.indexOf(this.cachePageList[cacheLength - 1]),
              1
            );
          cacheLength--;
        }
      })();
    },
    /** 清空缓存页面 */
    clearAllCachePage() {
      this.wholeMenus = [];
      this.cachePageList = [];
    }
  }
});

export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
